package com.aruba.paging3application

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.paging.LoadState
import androidx.recyclerview.widget.LinearLayoutManager
import com.aruba.paging3application.adapter.LoadMoreAdapter
import com.aruba.paging3application.adapter.MoviePagingAdapter
import com.aruba.paging3application.databinding.ActivityMainBinding
import com.aruba.paging3application.viewmodel.MovieViewModel
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

class MainActivity : AppCompatActivity() {
    private val movieViewModel by viewModels<MovieViewModel>()
    private val binding by lazy {
        ActivityMainBinding.inflate(layoutInflater)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        val adapter = MoviePagingAdapter()
        binding.apply {
            recyclerView.adapter = adapter.withLoadStateFooter(LoadMoreAdapter())
            recyclerView.layoutManager = LinearLayoutManager(this@MainActivity)

            //开始刷新
            refreshLayout.setOnRefreshListener {
                adapter.refresh()
            }
        }

        lifecycleScope.launchWhenCreated {
            launch {
                movieViewModel.bindPage().collect {
                    adapter.submitData(it)
                }   
            }
            
            launch {
                //监听adapter状态
                adapter.loadStateFlow.collect {
                    //根据刷新状态来通知swiprefreshLayout是否刷新完毕
                    binding.refreshLayout.isRefreshing = it.refresh is LoadState.Loading
                }
            }
        }
    }
}